package com.tbl.modules.wms2.controller.sale;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.wms2.constant.Constant;
import com.tbl.modules.wms2.controller.operation.YclInOutFlowController;
import com.tbl.modules.wms2.dao.production.YclMeterialOutDAO;
import com.tbl.modules.wms2.dao.sale.YclMeterSaleOutDAO;
import com.tbl.modules.wms2.entity.operation.YclInOutFlowEntity;
import com.tbl.modules.wms2.entity.sale.YclMaterialSaleOutEntity;
import com.tbl.modules.wms2.entity.sale.YclSaleEntity;
import com.tbl.modules.wms2.entity.sale.YclSaleLineEntity;
import com.tbl.modules.wms2.service.common.CountService;
import com.tbl.modules.wms2.service.sale.YclSaleOutLineService;
import com.tbl.modules.wms2.service.sale.YclSaleOutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 生产领料
 *
 * @author DASH
 */
@Controller
@RequestMapping(value = "/ycl/sale")
public class YclMaterialSaleOutController extends AbstractController {


    @Autowired
    private RoleService roleService;

    @Autowired
    private YclSaleOutService yclSaleOutService;

    @Autowired
    private YclSaleOutLineService yclSaleOutLineService;

    @Autowired
    private YclMeterSaleOutDAO yclMeterSaleOutDAO;

    @Autowired
    private YclMeterialOutDAO yclMeterialOutDAO;

    @Resource
    private YclInOutFlowController yclInOutFlowController;

    @Autowired
    private CountService countService;


    /**
     * 保存
     *
     * @param
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    @Transactional
    public Map<String, Object> save(@RequestBody List<Map> list) {
        Map<String, Object> ret_map = new HashMap<>(2);
        List<YclSaleLineEntity> yclSaleLineEntityList = new ArrayList<>();
        Map<String, Object> sale_info = list.get(0);
        YclSaleEntity yclSaleEntity = new YclSaleEntity();
        yclSaleEntity.setOutCode(RandomUtil.randomString(8));
        yclSaleEntity.setOrderCode(sale_info.get("orderNumber").toString());
        yclSaleEntity.setOrderType("销售订单");
        yclSaleEntity.setClient(sale_info.get("name").toString());
        yclSaleEntity.setAddress(sale_info.get("customerName").toString());
        yclSaleEntity.setAreaCode("A");
        yclSaleEntity.setStoreCode(null == sale_info.get("storeCode")?"":sale_info.get("storeCode").toString());
        yclSaleEntity.setTemporary(sale_info.get("stage").toString());
        yclSaleEntity.setShipment(null == sale_info.get("shipment")?"":sale_info.get("shipment").toString());
        yclSaleEntity.setRequest(null == sale_info.get("request")?"":sale_info.get("request").toString());
        yclSaleEntity.setConsigner(sale_info.get("organizationName").toString());

        yclSaleOutService.save(yclSaleEntity);
        for(Map map : list){
            YclSaleLineEntity yclSaleLineEntity = new YclSaleLineEntity();
            yclSaleLineEntity.setOutCode(RandomUtil.randomString(8));
            yclSaleLineEntity.setLocalCode(null == sale_info.get("storeCode")?"":sale_info.get("storeCode").toString());
            yclSaleLineEntity.setBatch((String) map.get("lotsNum"));
            yclSaleLineEntity.setMaterialCode((String) map.get("itemCode"));
            yclSaleLineEntity.setMaterialName((String) map.get("itemDesc"));
            yclSaleLineEntity.setQuality(map.get("outQuantity").toString());
            yclSaleLineEntity.setState("1");
            yclSaleLineEntityList.add(yclSaleLineEntity);

            YclInOutFlowEntity yclInOutFlowEntity = new YclInOutFlowEntity();
            yclInOutFlowEntity.setStoreCode(null == sale_info.get("storeCode")?"":sale_info.get("storeCode").toString());
            yclInOutFlowEntity.setAreaCode((String) map.get("orgId"));
            yclInOutFlowEntity.setLocatorCode((String) map.get("locatorCode"));
            yclInOutFlowEntity.setMaterialCode((String) map.get("itemCode"));
            yclInOutFlowEntity.setLotsNum((String) map.get("lotsNum"));
            yclInOutFlowEntity.setUpdownQuantity(new BigDecimal(map.get("outQuantity").toString()));
            yclInOutFlowEntity.setInoutType("0");
            yclInOutFlowController.save(yclInOutFlowEntity);
        }
        boolean result = yclSaleOutLineService.saveBatch(yclSaleLineEntityList);
        ret_map.put("result", result);
        ret_map.put("msg", result ? "保存成功！" : "保存失败！");
        return ret_map;
     }


    /**
     * 保存
     *
     * @param
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/saveSale")
    @ResponseBody
    @Transactional
    public Map<String, Object> saveSale(@RequestBody List<YclSaleLineEntity> yclSaleList) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Map<String, Object> resultMap = new HashMap<>(2);
        List<YclSaleLineEntity> yclSaleLineEntityList = new ArrayList<>();
//        Map<String, Object> sale_info = list.get(0);
        //获取一条数据
        YclSaleLineEntity yclSaleFirstLine = yclSaleList.get(0);

        //同步至EBS
        Map<String,Object> paramsMap = new HashMap();
        paramsMap.put("orderHeaderId",Long.parseLong(yclSaleFirstLine.getHeaderId()));
        paramsMap.put("requestCode",getSessionUser().getUsername());
        paramsMap.put("ruleName","A002_原材料销售");
        paramsMap.put("orgId",Long.parseLong(yclSaleFirstLine.getFactoryCode()));

        yclMeterialOutDAO.yclOrderOut(paramsMap);
        if (paramsMap.get("retCode").equals(Constant.ERROR)) {
            resultMap.put("code", 1);
            resultMap.put("msg", paramsMap.get("retMess"));
            return resultMap;
        }

        YclSaleEntity yclSaleEntity = new YclSaleEntity();
        String outCode = countService.getNextCount("XSCK");
        yclSaleEntity.setOutCode(outCode);
        yclSaleEntity.setOrderCode(yclSaleFirstLine.getOrderNumber());
        yclSaleEntity.setOrderType("销售订单");
        yclSaleEntity.setClient(yclSaleFirstLine.getName());
        yclSaleEntity.setAddress(yclSaleFirstLine.getCustomerName());
        yclSaleEntity.setAreaCode("A");
        yclSaleEntity.setStoreCode(yclSaleFirstLine.getStoreCode());
        yclSaleEntity.setTemporary(yclSaleFirstLine.getStage());
        yclSaleEntity.setShipment(sdf.format(new Date()));//发运时间
        yclSaleEntity.setRequest(sdf.format(new Date()));//请求时间
        yclSaleEntity.setConsigner(yclSaleFirstLine.getOrganizationName());
        yclSaleEntity.setLineId(yclSaleFirstLine.getLineId());

//        Map<String,Object>
//        yclMeterialOutDAO.yclOrderOut(paramsMap);

        yclSaleOutService.save(yclSaleEntity);
        for(YclSaleLineEntity line : yclSaleList){
             line.setOutCode(outCode);
            line.setState("1");
            line.setMaterialCode(line.getItemCode());
            line.setMaterialName(line.getItemDesc());
            line.setQuality(line.getOutQuantity());
            line.setBatch(line.getLotsNum());
            line.setLocalCode(line.getLocatorCode());
//            line.setLocalCode();
            yclSaleLineEntityList.add(line);
            YclInOutFlowEntity yclInOutFlowEntity = new YclInOutFlowEntity();
            yclInOutFlowEntity.setStoreCode(line.getStoreCode());
            yclInOutFlowEntity.setAreaCode(line.getOrgId());
            yclInOutFlowEntity.setLocatorCode(line.getLocalCode());
            yclInOutFlowEntity.setMaterialCode(line.getItemCode());
            yclInOutFlowEntity.setLotsNum(line.getLotsNum());
            yclInOutFlowEntity.setUpdownQuantity(new BigDecimal(line.getOutQuantity()));
            yclInOutFlowEntity.setInoutType("0");
            yclInOutFlowController.save(yclInOutFlowEntity);
        }
        boolean result = yclSaleOutLineService.saveBatch(yclSaleLineEntityList);

        resultMap.put("code", result ? 0: 1);
        resultMap.put("msg", result ? "操作成功" : "操作失败");

        return resultMap;
    }
     /**
     * 跳转Grid列表页
     *
     * @return
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toRewindList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(2L, MenuConstant.warehouselist));
        mv.setViewName("techbloom2/sale/list");
        return mv;
    }

    /**
     * 获取Grid列表数据
     *
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/outlist")
    @ResponseBody
    public Map<String, Object> outlist() {
        Map<String, Object> paramsMap = getAllParameter();
//        List<VWmsShopItemReqEntity> pageList = prodPickingDAO.getOutPageList(
//                paramsMap);
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", null);
//        map.put("count", pageList.size());
//        map.put("data", pageList);
        return map;
    }

    /**
     * 跳转编辑页
     *
     * @return
     */
    @RequestMapping(value = "/toAddOut")
    public ModelAndView toDetail(String id) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom2/production/picking/edit");
        return mv;
    }

    /**
     * 获取Grid列表数据
     *
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list() {
        Map<String, Object> paramsMap = getAllParameter();
        List<YclMaterialSaleOutEntity> pageList = yclMeterSaleOutDAO.getPageList(
                new Page(
                        Integer.parseInt((String) paramsMap.get("page")),
                        Integer.parseInt((String) paramsMap.get("limit"))),
                paramsMap);
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", null);
        map.put("count", yclMeterSaleOutDAO.count(paramsMap));
        map.put("data", pageList);
        return map;
    }

    /**
     * 获取Grid列表数据——手机端
     *
     * @return Map<String, Object>
     */
    @GetMapping(value = "/api/list")
    @ResponseBody
    public Map<String, Object> listApi(String lotsNum) {
        String itemCode = lotsNum.substring(1, 11);
        Map<String, Object> paramsMap = getAllParameter();
        List<YclMaterialSaleOutEntity> pageList = yclMeterSaleOutDAO.getPageListApi(
                new Page(Integer.parseInt((String)paramsMap.get("page")),
                         Integer.parseInt((String)paramsMap.get("limit"))), itemCode);
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", null);
        map.put("count", yclMeterSaleOutDAO.countApi(itemCode));
        map.put("data", pageList);
        return map;
    }

    /**
     * 销售订单查询界面使用
     * @param
     * @return
     */
    @RequestMapping("/list2")
    @ResponseBody
    public Map<String,Object> getPageList2(){
        Map<String,Object> paramsMap = getAllParameter();
        List<YclMaterialSaleOutEntity> pageList2 = yclMeterSaleOutDAO.getPageList2(
                new Page(
                        Integer.parseInt((String) paramsMap.get("page")),
                        Integer.parseInt((String) paramsMap.get("limit"))),
                paramsMap
        );
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", null);
        map.put("count", yclMeterSaleOutDAO.count(paramsMap));
        map.put("data", pageList2);
        return map;
    }


    /**
     * 本地查询已出库信息
     * @param
     * @return
     */
    @RequestMapping(value = "/getSaleLineByOutCode",method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String,Object>> getSaleLineByOutCode(String outCode){
        List resultList = yclMeterSaleOutDAO.getSaleLineByOutCode(outCode);
        return resultList;
    }



}
